package com.coderli.onecoder.server;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.serialization.ClassResolvers;
import org.jboss.netty.handler.codec.serialization.ObjectDecoder;
import org.jboss.netty.handler.codec.serialization.ObjectEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lihzh
 * @date 2012-5-30 下午3:21:51
 */
public class HypervisorServer {

	private static final Logger log = LoggerFactory.getLogger(HypervisorServer.class);
	private final int port;

	public HypervisorServer(int port) {
		this.port = port;
	}

	public void run() {
		ServerBootstrap bootstrap = new ServerBootstrap(
				new NioServerSocketChannelFactory(
						Executors.newCachedThreadPool(),
						Executors.newCachedThreadPool()));
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			public ChannelPipeline getPipeline() throws Exception {
				return Channels.pipeline(
						new ObjectEncoder(),
						new ObjectDecoder(ClassResolvers
								.cacheDisabled(getClass().getClassLoader())),
						new HypervisorServerHandler());
			}
		});
		bootstrap.bind(new InetSocketAddress(port));
		log.info("Netty server has been started.");
	}

	/**
	 * @param args
	 * @author lihzh
	 * @date 2012-5-30 下午3:21:51
	 */
	public static void main(String[] args) {
		// 配置Server
		log.info("Begin to start netty server.");
		int port = 8000;
		new HypervisorServer(port).run();
	}

}
